<?php

class DB_Shard {

	public static $rules = array(
		'range' => 'DB_Shard_Range',
		'stats' => 'DB_Shard_Stats',
		'table' => 'DB_Shard_Table',
		'remainder' => 'DB_Shard_Remainder',
	);

	public function factory($options, $shardKey) {

		$rule = $options['rule'];
		$rules = self::$rules;

		$ruleKeys = $options['keys'];
		if (!is_array($options['keys'])) {
			$ruleKeys = array($options['keys']);
		}

		// 如果ignoreShareKeys为true则忽略分库关键字，不需要报错
		if (!$options['config']['ignoreShareKeys']) {
			foreach ($ruleKeys as $key) {
				if (!$shardKey[$key]) {
					throw new Exception('shardKey invalid');
				}
			}
		}

		if (array_key_exists($rule, $rules)) {

			$class = $rules[$rule];
			return new $class($options, $shardKey);
		}

		throw new Exception('Rule not found');
	}

}
